<?php
namespace app\admin\controller;
use think\Db; //使用数据类库
use think\captcha\Captcha; //验证码
use think\facade\Session; //Session
use think\facade\Cookie; // cookie

class Login extends \think\Controller
{
    //登录
    public function login() {
        if ($_POST) {
            //接收验证码并且做验证
            $code = $this -> request -> post('code');
            if (!captcha_check($code)) {
                //没有通过验证
                $this -> error("验证码输入有误");
            }
            //验证用户名和密码
            $admin_name = $this -> request -> post('admin_name');
            $admin_password = md5($this -> request -> post('admin_password'));
            $admin = Db::name('admin') -> where("admin_name='$admin_name' AND admin_password='$admin_password'") -> find();
            if ($admin) {
                //验证通过
                Cookie::set('admin_name',$admin_name,3600); //有效期3600秒
                //设置 session
                Session::set('login','1');
                $this -> success('登录成功','/admin/index/index');
            }else {
                $this -> error('用户名或密码输入有误');
            }
        }
        return $this -> fetch();
    }
    //验证码
    public function verify() {
        $config = array(
            'length' => 4,
            'fontSize' => 30,
        );
        //加载配置
        $captcha = new Captcha($config);
        return $captcha->entry();
    }
}